package com.jecy.controller;

import cn.thinkjoy.cloudstack.dynconfig.DynConfigClientFactory;
import cn.thinkjoy.cloudstack.dynconfig.IChangeListener;
import cn.thinkjoy.cloudstack.dynconfig.domain.Configuration;
import cn.thinkjoy.common.Constants;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.qtone.open.QTOpenApiConfig;
import com.qtone.open.ucm.client.UserAgentCookieCredentialHelper;
import com.qtone.open.ucm.exception.CannotAuthException;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by huijun on 17/1/17.
 */
@Controller
public class LoginController {
    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    QTOpenApiConfig QTOAuthConfig;
    private String oauthLoginUrl;

    @PostConstruct
    public void init() {
        try {
            oauthLoginUrl = DynConfigClientFactory.getClient().getConfig("ucenter", "ucenter", "common", "oauthLoginUrl");
        } catch (Exception e) {
        }

        DynConfigClientFactory.getClient().registerListeners("ucenter", "ucenter", "common", "oauthLoginUrl", new IChangeListener() {
            @Override
            public Executor getExecutor() {
                return Executors.newSingleThreadExecutor();
            }

            @Override
            public void receiveConfigInfo(final Configuration configuration) {
                getExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        oauthLoginUrl = configuration.getConfig();

                    }
                });
            }
        });
    }
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie(Constants.CookieProductName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        Map<String, String[]> map = new HashMap<>();
        Map<String, String[]> requestmap = request.getParameterMap();
        map.putAll(requestmap);
        if (map.size() == 0) {
            map.put("debugKey", getArray(QTOAuthConfig.getDebugKey()));
            map.put("client_id", getArray(QTOAuthConfig.getClient_id()));
            map.put("client_secret", getArray(QTOAuthConfig.getClient_secret()));
            map.put("loginUrl", getArray(QTOAuthConfig.getLoginUrl()));
            map.put("validateTokenUrl", getArray(QTOAuthConfig.getValidateTokenUrl()));
            map.put("logoutPattern", getArray(QTOAuthConfig.getLogoutPattern()));
            map.put("redirectUrlAfterLogin", getArray(QTOAuthConfig.getRedirectUrlAfterLogin()));
            map.put("redirect_uri", getArray(QTOAuthConfig.getRedirectUrlAfterLogin()));
            map.put("redirectUrlAfterLogout", getArray(QTOAuthConfig.getRedirectUrlAfterLogout()));
            map.put("grant_type", getArray("password"));
            map.put("serverUri", getArray(QTOAuthConfig.getServerUri()));
            map.put("product", getArray(QTOAuthConfig.getProduct()));
            map.put("appKey", getArray(QTOAuthConfig.getAppKey()));
        }

        try {
            String token = UserAgentCookieCredentialHelper.extractToken(request);
            if (validateToken(token)) {
                StringBuilder url = null;
                if (map.containsKey("redirect_uri")) {
                    url = new StringBuilder(map.get("redirect_uri")[0]);
                    if (url.indexOf("?") > 0) {
                        url.append("&access_token=" + token);
                    } else {
                        url.append("?access_token=" + token);
                    }
                }
                response.sendRedirect(url.toString());
            }
        } catch (Exception ex) {

        }
        map.put("oauthLoginUrl", getArray(oauthLoginUrl));
        logger.debug(map.get("client_id") + "");
        String client_host = request.getServerName();
        String reffer = request.getHeader("Referer");
        if (StringUtils.isNotBlank(reffer)) {
            URL url = null;
            try {
                url = new URL(reffer);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            client_host = url.getHost();
        }
        //默认为login3
        ModelAndView mav = new ModelAndView("login");

        getLoginConfig(map.get("client_id")[0], client_host, mav);

        mav.addAllObjects(map);

        return mav;
    }

    private String[] getArray(String _val) {
        String[] arr = new String[1];
        arr[0] = _val;
        return arr;
    }

    private void getLoginConfig(String client_id, String host, ModelAndView mav) {
        Map<String, Object> map = new HashMap<>();
        map.put("clientId", client_id);
        map.put("host", host);
        /*LoginConfig loginConfig = (LoginConfig) loginConfigService.queryOne(map);
        if (loginConfig != null) {
            mav.addObject("config", loginConfig);
            if (StringUtils.isNotBlank(loginConfig.getLoginPage())) {
                mav.setViewName(loginConfig.getLoginPage());
            }
        }*/


    }

    private boolean validateToken(String token) {
        // TODO validate token
        if (Strings.isNullOrEmpty(token)) {
            return false;
        }

        OkHttpClient client = new OkHttpClient();
        try {
            String url = QTOAuthConfig.getValidateTokenUrl() + "?token=" + token;
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();


            if (response.isSuccessful()) {
                String json = response.body().string();
                Boolean result = JSON.parseObject(json).getJSONObject("bizData").getBoolean("result");
                return result;
            } else {
                throw new CannotAuthException("validateToken过程，请求返回失败");
            }
        } catch (IOException e) {
            throw new CannotAuthException("validateToken过程，网络请求不可用");
        }

    }
}
